package com.mfs.proxy.client.transfer.http.response;

import com.mfs.common.constant.Constant;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Http响应头
 *
 * @author mfs
 * @date 2023/7/18 23:03
 **/
public class HttpResponseHeader {
    private Map<String, String> heads = new HashMap<>();

    private boolean completed = false;

    public String getHead(String headName) {
        return heads.get(headName);
    }

    public void putHead(String headName, String headValue) {
        heads.put(headName, headValue);
    }

    public List<String> heads() {
        return new ArrayList<>(heads.keySet());
    }

    public boolean isCompleted() {
        return completed;
    }

    public void setCompleted(boolean completed) {
        this.completed = completed;
    }

    byte[] getBytes() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> item : heads.entrySet()) {
            sb.append(item.getKey() + Constant.COLON + Constant.BLANK_STRING + item.getValue() + "\r\n");
        }
        sb.append("\r\n");
        try {
            return sb.toString().getBytes("ascii");
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    @Override
    public String toString() {
        return heads.entrySet().stream().map(item -> item.getKey() + Constant.COLON + Constant.BLANK_STRING + item.getValue())
                .collect(Collectors.joining("\r\n"));
    }
}
